package com.atguigu.yygh.order.api;

import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeiXinService;
import com.atguigu.yygh.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author zr
 * @date 2021/12/22 20:29
 */
@Api(tags = "微信支付接口")
@RestController
@RequestMapping("/api/order/weixin")
public class WeiXinApiController {
    @Resource
    private WeiXinService weiXinService;
    @Resource
    private PaymentService paymentService;

    /**
     * 下单 生成二维码
     */
    @GetMapping("/createNative/{orderId}")
    public Result createNative(
            @ApiParam(name = "orderId", value = "订单id", required = true)
            @PathVariable("orderId") Long orderId) {
        Map map = weiXinService.createNative(orderId);
        return Result.ok(map);
    }

    @ApiOperation(value = "查询支付状态")
    @GetMapping("queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable Long orderId) {
        // 调用微信接口 查询支付状态
        Map<String, String> resultMap = weiXinService.queryPayStatus(orderId);
        if (resultMap == null) {
            return Result.fail().message("支付出错");
        }
        // 支付成功
        if ("SUCCESS".equals(resultMap.get("trade_state"))) {
            // 根据订单编号更新订单状态
            // 获取订单编号
            String outTradeNo = resultMap.get("out_trade_no");
            paymentService.paySuccess(outTradeNo, resultMap);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }
}
